<template>
  <div class="mt-picker-wrap mt-select-wrap mt-picker--{{disabled ? 'disabled' : 'inited'}}">
    <div
      class="mt-picker-trigger"
      @tap="onTriggerPopup"
    >
      <block wx:if="{{!inner_value || inner_value.length < 1 || inner_value[0] < 0 || !labeltext}}">
        <div class="mt-picker__init"><slot name="initial"></slot></div>
      </block>
      <block wx:else>
        <div class="mt-picker__content">
          <block wx:if="{{useSlot}}"><slot></slot></block>
          <block wx:else>{{labeltext}}</block>
        </div>
      </block>
      <div class="mt-picker__action"></div>
    </div>

    <van-popup
      show="{{ showPopup }}"
      position="bottom"
      overlay="{{ true }}"
      @click-overlay="onClickOverlay"
      overlay-style="background-color: rgba(0,0,0, .3)"
    >
      <div class="u-flex u-aic u-jcsb mt-picker__control">
        <div class="mt-picker__btn mt-picker__cancel" @tap="onCancel">取消</div>
        <div class="mt-picker__btn mt-picker__confirm" @tap="onConfirm">确定</div>
      </div>
      <div class="u-flex mt-reselect-labels" wx:for="{{tmpLabelsArr}}" wx:key="*this">
        <div bind:tap="chooseColumn" data-item="{{item}}"  data-index="{{index}}">{{item}}</div>
      </div>
      <swiper current="{{currentIndex}}">
        <block wx:for="{{inner_columns}}" wx:key="*this">
          <swiper-item>

            <view class="swiper-item {{index}}">
              <div wx:for="{{inner_columns[index]}}" wx:for-index="columnItemIndex" wx:for-item="columnItem"
                bind:tap="onBindTap" data-index="{{columnItemIndex}}" data-column-index="{{index}}"
                   wx:key="value"
              >
                {{columnItem.label}}
              </div>
            </view>
          </swiper-item>
        </block>
      </swiper>

    </van-popup>
  </div>
</template>

<script>
  const formEmitterBehavior = require('../../behaviors/emitter.behavior')
  const formELementBehavior = require('../../behaviors/form-element.behavior')


  const EMPTY_TEXT = '请选择'

//  Object.prototype.toString.call(newVal) === '[object Null]'

  function isEmpty(value) {
    return !value || value.length < 1 || value[0] < 0
  }

  export default {
    behaviors: [
      formEmitterBehavior,
      formELementBehavior
    ],
    relations: {
      '../mt-form-item/index': {
        type: 'ancestor', // 关联的目标节点应为祖先节点
        linked(v) {
          this.formItem = v
          // console.log('this.formItem', this.formItem)
        },
        unlinked() {
          this.formItem = null
        }
      }
    },
    observers: {
      'sModel': function (field) {
        console.log('mtreselect field', field)
        if (Array.isArray(field) ) {
          this.setModelChange(field)
        }
      }
    },
    properties: {
      sModel: null,
      indicatorStyle: {
        type: String,
        value: 'height: 50px;'
      },
      pickerStyle: {
        type: String,
        value: 'width: 100%; height: 200px;'
      },
      useSlot: {
        type: Boolean,
        value: false,
      },
      itemHeight: {
        type: Number,
        value: 40
      },
      disabled: {
        type: Boolean,
        value: false,
      },
      col: {
        type: Number,
        value: 3
      },
      columns: {
        type: null,
        value: null,
        observer(newVal) {
          console.log(newVal)
          let newValIsNull = (Object.prototype.toString.call(newVal) === '[object Null]')
          if (newValIsNull) {
            this.setData({
              inner_columns: [],
              inner_value: [],
              currentIndex: 0,
              tmpLabels: {},
              tmp: {}
            })
          } else {
             let d = {
                [0]: EMPTY_TEXT
              }
            // console.log('columns', parsedValue)
            this.setData({
              inner_columns: newVal,
              inner_value: [],
              currentIndex: 0,
              tmpLabels: d,
              tmp: {}
            })
          }
          // console.log('columns', newVal, this.data.inner_columns)
        }
      },
      index: {
        type: null,
        value: null,
        observer(newVal) {

        }
      },
      defaultIndex: {
        type: Array,
        value: []
      }
    },
    data() {
      return {
        inner_columns: [],
        inner_value: [],
        tmp_value: [],
        showPopup: false,
        labeltext: '',
        formItem: null,
        pickerReady: false,
        currentIndex: 0,
        tmpLabels: {},
        tmp: {},
      }
    },
    computed: {
      tmpLabelsArr(data) {
        if (!data.tmpLabels) {
          return []
        }
        return Object.values(data.tmpLabels)
      },
     },
    methods: {
      setModelChange(newVal) {
        console.log('mtreselect', newVal, this.data.columns)
        if (Array.isArray(this.data.columns)) {
          let tmp = {}
          newVal.forEach((newValItem, index) => {
            let column = this.data.columns[index]
            let findItem = column.find(columnItem => columnItem.value === newValItem)
            tmp[index] = findItem
          })
          let values = Object.values(tmp)
            console.log('mtreselect', tmp, values)
          let inner_value = values.map(v => v.value)
          let labeltext = values.map(v => v.label).join()
          let d = {
            tmpLabels: values.map(v => v.label),
            tmp,
            inner_value,
            labeltext,
            currentIndex: newVal.length - 1
          }
          this.setData(d)
        }
      },
      onTriggerPopup(e) {
        if (!this.data.disabled) {
          this.$native.emit('open-popup')
          this.setData({
            showPopup: true
          })
        }
      },
      getTmpLabels(index, currentIndex, append = false) {
        let obj = this.data.inner_columns[currentIndex][index]
        // console.log(currentIndex, obj)
        this.data.tmpLabels[currentIndex] = obj.label
        this.data.tmp[currentIndex] = obj
        if (currentIndex + 1 < this.data.col) {
          for (let m = currentIndex + 1; m < this.data.col; m++) {
            this.data.tmpLabels[m] = ''
          }
          if (append) {
            this.data.tmpLabels[currentIndex + 1] = EMPTY_TEXT
          }
        }
        return {
          tmp: this.data.tmp,
          tmpLabels: this.data.tmpLabels,
        }
      },
      resetIndex() {

      },
      onClickOverlay() {
        this.resetIndex()
        this.$native.emit('close-popup')
        wx.nextTick(() => {
          this.setData({
            showPopup: false
          })
        })
      },
      onCancel() {
        this.resetIndex()
        this.$native.emit('close-popup')
        wx.nextTick(() => {
          this.setData({
            showPopup: false
          })
        })
      },
      onConfirm() {
        let d = {}
        let items = Object.values(this.data.tmp)
        // console.log(items, this.data.col)
        if (items.length < this.data.col) {
          // 没选完不处理
        } else {
          d.labeltext = items.map(v => v.label).join()
          d.inner_value = items.map(v => v.value)
          d.showPopup = false
          this.setData(d)
          this.fireChange(d.inner_value)
          this.$native.emit('close-popup')
        }
      },
      fireChange(newVal) {
        // console.log('mtreselect fireChange', newVal)
        let formValue = newVal.join()
        this.$native.emit('change', {
          value: formValue
        })
        this.callComponent(this.formItem, 'mtFormChange', [formValue])
      },
      onBindTap(e) {
        let { dataset } = e.target
        // console.log(dataset)
        let d = {
          tmp_value: [dataset.index],
          ...this.getTmpLabels(dataset.index, dataset.columnIndex, true),
        }
        if (dataset.columnIndex < this.data.col - 1) {
          d.currentIndex =  dataset.columnIndex + 1
        }
        this.setData(d)
      },
      chooseColumn(e) {
        let { dataset } = e.target
        let columnIndex = parseInt(dataset.index)
        this.changeColumnIndex(columnIndex, dataset.item)
      },
      changeColumnIndex(columnIndex, item) {
        // console.log(item)
        if (item === EMPTY_TEXT) {

        } else {
          this.setData({
            currentIndex: columnIndex,
            // ...this.getTmpLabels(0, columnIndex, false)
          })
        }
      }
    },
  }
</script>

<style lang="less">
  @import "../../app.component.less";

  .mt-reselect-labels {
    margin-bottom: 20rpx;
  }
</style>
